package com.yonyou.brigade.order_center.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.yonyou.brigade.basic_init.enums.ChannelEnum;
import com.yonyou.brigade.basic_init.model.IChannelConfig;
import com.yonyou.brigade.basic_init.service.IBriChannelService;
import com.yonyou.brigade.order_center.model.CLYHConfig;
import com.yonyou.brigade.util.operateutil.CompareUtils;
import com.yonyou.brigade.util.operateutil.RedisUtils;
import com.yonyou.brigade.util.resultutil.HttpSendUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by Administrator on 2018/10/18.
 */
@Service
public class YHUtils {

    @Value("${yihao.url.tokenurl}")
    private  String TOKEN_URL;

    @Autowired
    private RedisUtils redisUtils;

    private Logger logger= LoggerFactory.getLogger(this.getClass());
    /**
     * 获取差旅壹号access_token
     * @param
     * @return
     */
    public  String getToken(String tenant, String requestid, JSONObject config){
        String redisKey = "_".concat(tenant).concat("_").concat(config.getString("appid"));
        String resultStr = "";
        try {
            if (tenant.equals(redisUtils.getValue("tenant".concat(redisKey)))
                    && (StringUtils.isEmpty(config.getString("appid")) ? "" : config.getString("appid")).equals(redisUtils.getValue("appid".concat(redisKey)))
                    && redisUtils.hasKey("access_token_clyh".concat(redisKey))){
                resultStr = redisUtils.getValue("access_token_clyh".concat(redisKey));
                logger.info("从redis中获取租户" + tenant + "差旅壹号access_token ：" + resultStr);
            }else {
                Map<String,Object> paramsMap = new HashMap<>();
                paramsMap.put("requestid",requestid);
                paramsMap.put("version",config.getString("version"));
                Map<String,String> params = new HashMap<>();
                params.put("appid",config.getString("appid"));
                params.put("appsecret",config.getString("appsecret"));
                paramsMap.put("data",params);
                String responseStr = "";
                for (int i = 0; i < 3;i++ ){
                    logger.info("请求差旅壹号token参数： " + JSON.toJSONString(paramsMap));
                    responseStr = HttpSendUtils.sendPost(TOKEN_URL, JSON.toJSONString(paramsMap));
                    if (!StringUtils.isEmpty(responseStr)){
                        logger.info("请求差旅壹号返回token结果： " + responseStr);
                        JSONObject tokenJson = JSON.parseObject(responseStr);
                        //返回结果
                        if (tokenJson.getJSONObject("data") == null) {
                            continue;
                        }
                        resultStr = tokenJson.getJSONObject("data").getString("access_token");
                        //将获取到的token 存入redis，有效时间60分钟
                        redisUtils.setKey("access_token_clyh".concat(redisKey), resultStr,60);
                        redisUtils.setKey("tenant".concat(redisKey), tenant,60);
                        redisUtils.setKey("appid".concat(redisKey), config.getString("appid"));
                        break;
                    }
                }
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        return resultStr;
    }

    /**
     * 比较两个对象的某些字段是否有差异
     * @param compareFields 做比较的字段
     * @param compareMap 差异字段
     * @param source 源对象
     * @param target 目标对象
     * @return
     */
    public Map<String, Object> compareFields(String[] compareFields, Map<String, String> compareMap, Object source, Object target){
        if (compareFields != null && compareFields.length > 0) {
            for (int i = 0; i < compareFields.length; i++) {
                //此处只需要key值
                compareMap.put(compareFields[i], "");
            }
        }
        return CompareUtils.getModifyContent(source, target, compareMap);
    }
}